package com.bigchun.woodhunter;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import adapter.GoodsRecyclerViewAdapter;
import bean.ContentDataBean;
import bean.GoodsBean;
import myapp.MyApp;
import myview.CustomProgressDialog;
import myview.PullLoadMoreRecyclerView;
import myview.XCFlowLayout;
import util.MyLog;
import util.RequestManager;
import util.SystemStatusManager;
import util.utils;

public class SearchZhantingResultActivity extends BaseActivity {


    private LinearLayout ll_reback;
    private LinearLayout ll_nodata;
    private Context context;
    private MyApp myapp;
    private String token;
    private List<GoodsBean.DataBean> temgoodsList = new ArrayList<>();
    private List<GoodsBean.DataBean> goodsList = new ArrayList<>();
    private XCFlowLayout flowlayout;
    private LayoutInflater mInflater;
    private EditText et_searchtab;
    private TextView tv_search;
    private String searchcontent = "";
    private int page = 1;
    private int size = 10;
    private PullLoadMoreRecyclerView goodsRecycleView;
    private GoodsRecyclerViewAdapter adapter;
    private int width;
    private int heightPixels;
    private View bottomView;
    private LinearLayout loadLlay;
    private String apptype = "";
    private String textData;
    private SharedPreferences sharedPreferences;
    private CustomProgressDialog customProgressDialog;
    private String showroom;
    private ContentDataBean.DataBean textContent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_searchresult);
        setTranslucentStatus();
        context = this;
        myapp = (MyApp) getApplicationContext();
        sharedPreferences = getSharedPreferences("userInfo", Context.MODE_PRIVATE);
        token = sharedPreferences.getString("token", "");
        apptype = sharedPreferences.getString("apptype", "0");
        mInflater = LayoutInflater.from(context);
        searchcontent = getIntent().getStringExtra("searchcontent");
        showroom = getIntent().getStringExtra("showroom");
        textData = sharedPreferences.getString("textData", "");

        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        customProgressDialog.show();
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount=0f;   //取值为0-1之间  1是全黑
//		params.width = 180;//设置进度条的宽度
//		params.height = 180;//设置进度条的宽度
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();

        getScreenDen();
        initView();
        initTopView();
        initLin();
        getData();


    }


    private void initView() {
        ll_reback = findViewById(R.id.ll_reback);
        ll_nodata = findViewById(R.id.ll_nodata);
        flowlayout = findViewById(R.id.flowlayout);
        et_searchtab = findViewById(R.id.et_searchtab);
        tv_search = findViewById(R.id.tv_search);
        et_searchtab.setText(searchcontent);
        et_searchtab.setSelection(searchcontent.length());
        TextView tv_nodata = findViewById(R.id.tv_nodata);
        TextView tv_title = findViewById(R.id.tv_title);
        textContent = new Gson().fromJson(textData, new TypeToken<ContentDataBean.DataBean>() {}.getType());
        if (textContent != null){
            tv_title.setText(textContent.getSearch());
            et_searchtab.setHint(textContent.getInput_search_con());
            tv_search.setText(textContent.getSearch());
            tv_nodata.setText(textContent.getNodata());
        }

        goodsRecycleView = findViewById(R.id.rclv_goods);
        adapter = new GoodsRecyclerViewAdapter(temgoodsList, context, myapp,width, textContent);
        setHeader(goodsRecycleView);
        goodsRecycleView.setAdapter(adapter);
        goodsRecycleView.setGridLayout(2);
        goodsRecycleView.setRefreshing(true);
    }
    /**
     * 设置头部布局
     *
     * @param view
     */
    private void setHeader(PullLoadMoreRecyclerView view) {


        //底部加载更多
        bottomView = LayoutInflater.from(context).inflate(R.layout.main_bottom, view, false);
        adapter.setBottomView(bottomView);
    }
    /**
     * 初始化头部控件
     */
    private void initTopView() {


        //加载更多
        loadLlay = (LinearLayout) bottomView.findViewById(R.id.llay_load);
    }
    //只是关闭软键盘
    private void closeKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && getCurrentFocus() != null) {
            if (getCurrentFocus().getWindowToken() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    private void initLin() {
        ll_reback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        tv_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (utils.isFastDoubleClick()){
                    return;
                }
                searchcontent = et_searchtab.getText().toString().trim();
                if (!"".equals(searchcontent)){
                    temgoodsList.clear();
                    adapter.setDatas(temgoodsList);
                    adapter.notifyDataSetChanged();
                    page = 1;
                    customProgressDialog.show();
                    getData();
                    closeKeyboard();
                }
            }
        });

        goodsRecycleView.setOnPullLoadMoreListener(new PullLoadMoreRecyclerView.PullLoadMoreListener() {
            @Override
            public void onRefresh() {
                page = 1;
                getData();
//                goodsRecycleView.setPullLoadMoreCompleted();
            }

            @Override
            public void onLoadMore() {
                if (temgoodsList.size() != 0){
                page++;
                customProgressDialog.show();
                getData();
                }else{
                goodsRecycleView.setPullLoadMoreCompleted();

                }
            }

            @Override
            public void onScrollChanged(int heightTotal) {

            }

            @Override
            public void onScrollState(int type) {

            }
        });
        //店铺列表点击事件
        adapter.setOnItemClickListener(new GoodsRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                MyLog.e("条目点击事件",position+"    item");
                int id = goodsList.get(position).getId();
                Intent intent = new Intent(context, GoodsInfomationActivity.class);
                intent.putExtra("goodsid",id+"");
                startActivity(intent);
            }
        });

    }

    /**
     * 获取搜索内容标签
     */
    private void getData() {

        String url = myapp.getWebConfig() + "/api/index/gallery_search";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("token", token);
        paramsMap.put("gallery", showroom);
        paramsMap.put("search", searchcontent);
        paramsMap.put("page", page+"");
        paramsMap.put("size", size+"");
        paramsMap.put("is_material", apptype);
        MyLog.e("搜索参数",token+"  "+showroom+"  "+searchcontent+"  "+page+"   "+size+"  "+apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {

                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handler.sendMessage(msg);
                        return;
                    }
                    JSONArray data = jsonObject.getJSONArray("data");
                    temgoodsList = new Gson().fromJson(data.toString(), new TypeToken<List<GoodsBean.DataBean>>() {
                    }.getType());


                    msg.arg1 = 2;
                    handler.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handler.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                MyLog.e("result", errorMsg);
                if (errorMsg.equals("未登录")){
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handler.sendMessage(msg);
                }
            }
        });
    }
    public Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    String str = (String) msg.obj;
                    Toast.makeText(context, str, Toast.LENGTH_LONG).show();
                    break;
                case 1:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    Toast.makeText(context, textContent.getNet_error(), Toast.LENGTH_LONG).show();
                    break;
                case 2:
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    if (page == 1) {
                        goodsList.clear();
                    }
                    goodsList.addAll(temgoodsList);
                    adapter.setDatas(goodsList);
                    loadLlay.removeAllViews();
                    goodsRecycleView.setPullLoadMoreCompleted();

                    if (goodsList.size() == 0){
                        ll_nodata.setVisibility(View.VISIBLE);
                        goodsRecycleView.setVisibility(View.GONE);
                    }else{
                        ll_nodata.setVisibility(View.GONE);
                        goodsRecycleView.setVisibility(View.VISIBLE);
                    }
                    break;
                case 3:



                    break;
                case 4:

                    break;
                case 11:
                    if (!islogin){
                        islogin = true;
                        sharedPreferences.edit().putString("token", "").commit();
                        Intent intent = new Intent(context, LoginActivity.class);
                        context.startActivity(intent);
                        myapp.destoryActivity("主页面");
                    }
                    break;
            }
        }
    };
private boolean islogin = false;
    /**
     * 设置状态栏背景状态
     */
    public  void setTranslucentStatus()
    {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
        {
            Window win =  getWindow();
            WindowManager.LayoutParams winParams = win.getAttributes();
            final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
            winParams.flags |= bits;
            win.setAttributes(winParams);
        }
        SystemStatusManager tintManager = new SystemStatusManager(this);
        tintManager.setStatusBarTintEnabled(true);
        tintManager.setStatusBarTintResource(0);//状态栏无背景
    }
    /**
     * 获取屏幕宽度
     */
    private void getScreenDen() {

        WindowManager manager = getWindowManager();
        DisplayMetrics dm = new DisplayMetrics();
        manager.getDefaultDisplay().getMetrics(dm);
        //以要素为单位
        width = dm.widthPixels;
        heightPixels = dm.heightPixels;
        MyLog.e("获取屏幕高度", heightPixels + "    高度");
    }
}
